package jdbc.myDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

public class EmpDao {
	private DataSource dataSource;
	
	public EmpDao(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	public void add(Emp emp){
		try {
			Connection conn = dataSource.getConnection();
			PreparedStatement statement=
					conn.prepareStatement("insert into test_domain values(?,?,?,?)");
			statement.setInt(1, emp.getId());
			statement.setString(2, emp.getName());
			statement.setDouble(3, emp.getSalary());
			statement.setInt(4,emp.getAge());
			statement.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
	}
	
	
	public List<Emp> get(){
		List<Emp> emps = new ArrayList<Emp>();
		ResultSet rs=null;
		Connection conn=null;
		Statement statement = null;
		try {
			conn = dataSource.getConnection();
		    statement = conn.createStatement();
			String sql = "select * from test_domain";
			 rs = statement.executeQuery(sql);
			while(rs.next()){
				Emp emp = new Emp();
				emp.setId(rs.getInt("id"));
				emp.setName(rs.getString("name"));
				emp.setSalary(Double.parseDouble(rs.getString("salary")));
				emp.setAge(rs.getInt("age"));
				emps.add(emp);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return emps;
	}



}
